﻿using System;
using System.Collections.Generic;
using NReader.Model.RAS;
using NReader.Service;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using XnReader.WinRT.Controlx;
using XnReader.WinRT.Helper;

// “分组项页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234231 上提供

namespace XnReader.WinRT.Forms
{
    /// <summary>
    /// 显示分组的项集合的页。
    /// </summary>
    public sealed partial class OnlineArticleList
    {
        public OnlineArticleList()
        {
            InitializeComponent();
            var visiblesFooter = new CommandInfo
            {
                VisibleSearch = Visibility.Visible,
                VisibleBookcase = Visibility.Visible
            };
            if (header != null)
            {
                header.DataContext = visiblesFooter;
                //header.SettingClickEvent += HeaderSettingClickEvent;
            }
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (navigationParameter.ToString().StartsWith("search"))
            {
                try
                {
                    pbLoading.IsActive = true;
                    var queryString = navigationParameter.ToString().Replace("search", string.Empty);
                    var count = await ArticleService.Instance().SearchArticleListCount(queryString);
                    txtTotal.Text = string.Format("(搜索关键字“{0}”:共{1}本)", queryString, count);
                    _searchArticleList = new SearchArticleListPage<ArticleInfo>((uint)count, queryString);
                    cvsList.Source = _searchArticleList;
                }
                catch (Exception)
                {
                    var md = new MessageDialog("查询失败.请检查您的网络链接是否正确");
                    md.ShowAsync();
                    //throw;
                }
                finally
                {
                    pbLoading.IsActive = false;
                }
            }
            else
            {
                var sortid = 1001;
                if (!string.IsNullOrEmpty(navigationParameter.ToString()))
                {
                    sortid = int.Parse(navigationParameter.ToString());
                }
                navTop.SelectItem(sortid);
                DataBinding(sortid);
            }
        }

        #region 分类列表展示

        private ArticleListIncrementalLoadingClass<ArticleInfo> _articleList;

        private async void DataBinding(int sortid)
        {
            pbLoading.IsActive = true;
            try
            {
                var count = await NReader.Service.ArticleService.Instance().GetArticleListCountBySort(sortid);
                txtTotal.Text = string.Format("({0}:共{1}本)", GetSortName(sortid), count);
                _articleList = new ArticleListIncrementalLoadingClass<ArticleInfo>((uint)count, (uint)sortid);
                cvsList.Source = _articleList;
            }
            catch (Exception ex)
            {
                var md = new MessageDialog(string.Format("书籍列表加载错误.错误信息为：\r\n{0}", ex.Message));
                md.ShowAsync();
            }
            finally
            {
                pbLoading.IsActive = false;
            }
        }

        /// <summary>
        /// 根据ID获取类别名称
        /// </summary>
        /// <param name="sortid"></param>
        /// <returns></returns>
        private static string GetSortName(int sortid)
        {
            switch (sortid)
            {
                case 1001:
                    return "⛺ 最新更新";
                case 1:
                    return "✡ 玄幻奇幻";
                case 2:
                    return "☯ 武侠仙侠";
                case 3:
                    return "⚭ 都市言情";
                case 4:
                    return "☭ 历史军事";
                case 5:
                    return "⚽ 游戏竞技";
                case 6:
                    return "⚛ 科幻灵异";
                case 7:
                    return "⚘ 漫画同人";
                case 101:
                    return "❁ 全本阅读";
                case 1002:
                    return "☉ 点击排行榜";
                case 1003:
                    return "☺ 推荐排行榜";
            }
            return string.Empty;
        }

        #endregion

        #region 查询列表展示

        private SearchArticleListPage<ArticleInfo> _searchArticleList;

        #endregion

        private void ItemGridViewItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem != null)
            {
                int articleid = ((ArticleInfo)e.ClickedItem).articleid;
                Frame.Navigate(typeof(Book), articleid);
            }
        }

        #region 设置

        //private static IList<SysWebInfo> _sysWebInfos;

        ///// <summary>
        ///// 点击设置
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //async void  HeaderSettingClickEvent(object sender, RoutedEventArgs e)
        //{
        //    if (_sysWebInfos == null)
        //    {
        //        //网络连接错误
        //        if (await Helper.GlobalUtils.CheckConnectionState() == false)
        //        {
        //            _sysWebInfos = await GlobalService.Instance().GetSysWebInfosFromLocal();
        //        }
        //        else
        //        {
        //            _sysWebInfos = await GlobalService.Instance().GetSysWebList();
        //        }
        //    }
        //    if (_sysWebInfos != null)
        //    {
        //        cvsWebinfos.Source = _sysWebInfos;
        //    }

        //    borderSetting.Width = 300;
        //    borderSetting.Height = Window.Current.Bounds.Height;
        //    //popSetting.HorizontalOffset = Window.Current.Bounds.Width - 300;
        //    popSetting.IsOpen = true;
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void BarNavOpened(object sender, object e)
        //{
        //    if (popSetting.IsOpen) popSetting.IsOpen = false;
        //}

        #endregion
    }
}
